<template>
  <div class='task-wrap w-full top-[1000px] absolute left-0'>
    <div class='p-8 pb-0 h-full m-auto w-[1500px] border border-b-0 overflow-y-auto'>
      <Card class='mb-8'>
        <div class='flex items-center justify-between'>
          <Checkbox v-model='isSelectAll' @change='changeSelectAll'><span class='ml-1'>全选</span></Checkbox>
          <div class='flex-1 flex ml-2'>
            <Input v-model='searchName' placeholder='请输入名称' class='mr-2' style='width: 300px' />
            <Select class='mr-2 !w-[100px]' placeholder='请选择类型' v-model='type'>
              <Option :value='1'>待执行</Option>
              <Option :value='2'>已完成</Option>
              <Option :value='3'>已拒绝</Option>
              <Option :value='4'>已删除</Option>
            </Select>
            <Button type='primary' icon='md-search' @click='refresh'>
              搜索
            </Button>
          </div>
          <div class='flex' v-if='list.length > 0'>
            <div class='flex'>
              <Button v-if='this.searchType == 1' class='mr-2' type='error' icon='md-trash' @click='delList'>
                删除
              </Button>
              <Button v-if='this.searchType == 1' type='warning' class='mr-2' icon='md-hand' @click='finishAll(false)'>
                拒绝
              </Button>
              <Button class='mr-2' v-if='this.searchType == 1' type='primary' icon='md-checkmark'
                      @click='finishAll(true)'>
                完成
              </Button>
            </div>
            <Button icon='md-copy' @click='copySelect'>
              复制SQL
            </Button>
          </div>
        </div>
      </Card>
      <transition-group name='fade'>
        <div class='h-[336px]' :key='item.id' v-for='item in list'>
          <task-box :type='searchType' :nowIndex='nowIndex' @refresh='refresh' @finish='finish' :item='item'></task-box>
        </div>
        <div class='m-auto transition-all flex justify-center text-base text-gray-400 items-center w-full'
             v-if='list.length == 0 && !isFetch'>
          没有查询到任务！！！
        </div>
      </transition-group>
    </div>
    <base-modal ref='baseModelRef'></base-modal>
  </div>
</template>

<script>
import TaskBox from '@/components/TaskBox.vue'
import axios from 'axios'
import { HTTP_API } from '@/global/global'
import { busOff, busOn } from '@/tool/busTool'
import { copyToClipboard, getPrefix, getSuffix } from '@/tool/textTool'
import BaseModal from '@/components/BaseModal.vue'

export default {
  name: 'TaskWrap',
  components: { BaseModal, TaskBox },
  props: {
    nowIndex: Number
  },
  data() {
    return {
      isFetch: false,
      originIndex: null,
      isSelectAll: false,
      searchName: '',
      type: 1,
      searchType: 1,
      list: []
    }
  },
  mounted() {
    busOn('refreshTask', this.reload)
  },
  unmounted() {
    busOff('refreshTask', this.reload)
  },
  watch: {
    list: {
      handler() {
        if (this.list.length == 0) {
          this.isSelectAll = false
        } else {
          const index = this.list.findIndex((item) => !item.selected)
          this.isSelectAll = index < 0
        }
      },
      deep: true
    },
    type() {
      this.refresh()
    }
  },
  methods: {
    reload() {
      this.init()
      this.refresh()
    },
    init() {
      this.searchName = ''
      this.type = 1
      this.searchType = 1
      this.list = []
    },
    async fetchList() {
      if (this.isFetch) {
        return
      }
      this.isFetch = true
      try {
        let res = null
        this.list.length = 0
        if (this.type == 1) {
          const formData = new FormData()
          formData.append('endIndex', this.originIndex)
          formData.append('searchName', this.searchName)
          res = await axios.post(HTTP_API + '/task/listToDo', formData)
        }
        if (this.type == 2) {
          const formData = new FormData()
          formData.append('endIndex', this.originIndex)
          formData.append('searchName', this.searchName)
          res = await axios.post(HTTP_API + '/task/listFinish', formData)
        }
        if (this.type == 3) {
          const formData = new FormData()
          formData.append('endIndex', this.originIndex)
          formData.append('searchName', this.searchName)
          res = await axios.post(HTTP_API + '/task/listAbort', formData)
        }
        if (this.type == 4) {
          const formData = new FormData()
          formData.append('endIndex', this.originIndex)
          formData.append('searchName', this.searchName)
          res = await axios.post(HTTP_API + '/task/listDel', formData)
        }
        this.list.push(...res.data.map(item => {
          item.selected = false
          return item
        }))
        this.searchType = this.type
      } finally {
        this.isFetch = false
      }
    },
    copySelect() {
      let selectList = this.list.filter(item => item.selected)
      if (selectList.length == 0) {
        this.$Message.error('请选择任务')
        return
      }
      let text = ''
      for (let item of selectList) {
        text += getPrefix(item)
        text += item.content
        text += getSuffix(item)
      }
      copyToClipboard(text)
      this.$Message.success('复制成功')
    },
    finishAll(flag) {
      let selectList = this.list.filter(item => item.selected)
      if (selectList.length == 0) {
        this.$Message.error('请选择任务')
        return
      }
      this.$refs.baseModelRef.show('提示', flag ? '是否完成选中的任务' : '是否拒绝选中的任务', async () => {
        try {
          await axios.request({
            method: 'post', url: HTTP_API + '/task/finishTaskList', params: {
              flag: flag
            }, data: selectList.map(item => item.id)
          })
          this.$Message.success(flag ? '任务已完成' : '任务已拒绝')
        } catch (err) {
          console.error(err)
          this.$Message.error(flag ? '任务完成失败' : '任务拒绝失败')
        } finally {
          this.refresh()
        }
      })
    },
    delList() {
      let selectList = this.list.filter(item => item.selected)
      if (selectList.length == 0) {
        this.$Message.error('请选择任务')
        return
      }
      this.$refs.baseModelRef.show('提示', '是否删除选中的任务', async () => {
        try {
          await axios.request({
            method: 'post', url: HTTP_API + '/task/delList', data: selectList.map(item => item.id)
          })
          this.$Message.success('删除成功')
        } catch (err) {
          console.error(err)
          this.$Message.error('删除失败')
        } finally {
          this.refresh()
        }
      })
    },
    changeSelectAll(event) {
      if (event.target.checked) {
        for (let item of this.list) {
          item.selected = true
        }
      } else {
        for (let item of this.list) {
          item.selected = false
        }
      }
    },
    refresh() {
      if (this.originIndex) {
        this.fetchList()
      }
    },
    show(originIndex) {
      this.originIndex = originIndex
      this.reload()
    },
    finish() {
    }
  }
}
</script>

<style scoped>
.fade-enter-active,
.fade-leave-active {
  transition: all 0.5s;
}

.fade-enter,
.fade-leave-to {
  opacity: 0;
  height: 0;
}

.task-wrap {
  height: calc(100vh - 188px);
}

.task-wrap > div {
  box-shadow: -1px 0px 14px 0px rgba(50, 50, 50, 0.25);
}
</style>